package com.lwl.personal_practice;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class SpinnerDropdownActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_dropdown);
        initSpinnerForDropdown();
    }
    private void initSpinnerForDropdown(){
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this,
                R.layout.item_select,starArray);
        Spinner sp_dropdown = findViewById(R.id.sp_dropdown);
        sp_dropdown.setPrompt("请选择行星");
        sp_dropdown.setAdapter(starAdapter);
        sp_dropdown.setSelection(0);
        sp_dropdown.setOnItemSelectedListener(new MySelectedListener());;
    }
    private String[] starArray = {"水星", "金星", "地球", "火星", "木星", "土星"};

    private class MySelectedListener implements AdapterView.OnItemSelectedListener {
        // 选择事件的处理方法，其中arg2代表选择项的序号
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Toast.makeText(SpinnerDropdownActivity.this, "您选择的是" + starArray[arg2],
                    Toast.LENGTH_LONG).show();
        }

        // 未选择时的处理方法，通常无需关注
        public void onNothingSelected(AdapterView<?> arg0) {}
    }
}